篇首语:本文由编程笔记#小编为大家整理,主要介绍了[死磕 Spring 37/43] --- IOC 之 bean 的实例化策略: InstantiationStrategy相关的知识,希望对你有一定的参考价值。
引用原文:
https://www.cmsblogs.com/article/1391375583832838144
[死磕 Spring 37/43] — IOC 之 bean 的实例化策略: InstantiationStrategy
instantiation [ɪnstænʃɪ’eɪʃən] 实例化,例示;
在开始分析 InstantiationStrategy 之前,我们先来简单回顾下 bean 的实例化过程:
InstantiationStrategy 接口定义了 Spring Bean 实例化的策略,根据创建对象情况的不同,提供了三种策略:无参构造方法、有参构造方法、工厂方法。如下:
public interface InstantiationStrategy
/**
* 默认构造方法
*/
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)
throws BeansException;
/**
* 指定构造方法
*/
Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
Constructor<?> ctor, &#64;Nullable Object... args) throws BeansException;
/**
* 工厂方法
*/
Object instantiate(RootBeanDefinition bd, &#64;Nullable String beanName, BeanFactory owner,
&#64;Nullable Object factoryBean, Method factoryMethod, &#64;Nullable Object... args)
throws BeansException;
InstantiationStrategy 接口有两个实现类&#xff1a;SimpleInstantiationStrategy 和 CglibSubclassingInstantiationStrategy。SimpleInstantiationStrategy 对以上三个方法都做了简单的实现。
如果是工厂方法实例化&#xff0c;则直接使用反射创建对象&#xff0c;如下&#xff1a;
public Object instantiate(RootBeanDefinition bd, &#64;Nullable String beanName, BeanFactory owner,
&#64;Nullable Object factoryBean, final Method factoryMethod, &#64;Nullable Object... args)
try
if (System.getSecurityManager() !&#61; null)
AccessController.doPrivileged((PrivilegedAction<Object>) () ->
ReflectionUtils.makeAccessible(factoryMethod);
return null;
);
else
ReflectionUtils.makeAccessible(factoryMethod);
Method priorInvokedFactoryMethod &#61; currentlyInvokedFactoryMethod.get();
try
currentlyInvokedFactoryMethod.set(factoryMethod);
Object result &#61; factoryMethod.invoke(factoryBean, args);
if (result &#61;&#61; null)
result &#61; new NullBean();
return result;
finally
if (priorInvokedFactoryMethod !&#61; null)
currentlyInvokedFactoryMethod.set(priorInvokedFactoryMethod);
else
currentlyInvokedFactoryMethod.remove();
// 省略 catch
如果是构造方法实例化&#xff0c;则是先判断是否有 MethodOverrides&#xff0c;如果没有则是直接使用反射&#xff0c;如果有则就需要 CGLIB 实例化对象。如下&#xff1a;
public Object instantiate(RootBeanDefinition bd, &#64;Nullable String beanName, BeanFactory owner)
// Don&#39;t override the class with CGLIB if no overrides.
if (!bd.hasMethodOverrides())
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock)
constructorToUse &#61; (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse &#61;&#61; null)
final Class<?> clazz &#61; bd.getBeanClass();
if (clazz.isInterface())
throw new BeanInstantiationException(clazz, "Specified class is an interface");
try
if (System.getSecurityManager() !&#61; null)
constructorToUse &#61; AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
else
constructorToUse &#61; clazz.getDeclaredConstructor();
bd.resolvedConstructorOrFactoryMethod &#61; constructorToUse;
catch (Throwable ex)
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
return BeanUtils.instantiateClass(constructorToUse);
else
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
public Object instantiate(RootBeanDefinition bd, &#64;Nullable String beanName, BeanFactory owner,
final Constructor<?> ctor, &#64;Nullable Object... args)
if (!bd.hasMethodOverrides())
if (System.getSecurityManager() !&#61; null)
// use own privileged to change accessibility (when security is on)
AccessController.doPrivileged((PrivilegedAction<Object>) () ->
ReflectionUtils.makeAccessible(ctor);
return null;
);
return (args !&#61; null ? BeanUtils.instantiateClass(ctor, args) : BeanUtils.instantiateClass(ctor));
else
return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
SimpleInstantiationStrategy 对 instantiateWithMethodInjection() 的实现任务交给了子类 CglibSubclassingInstantiationStrategy。
对于 MethodOverrides&#xff0c;如果读者是跟着小编文章一路跟过来的话一定不会陌生&#xff0c;在 BeanDefinitionParserDelegate 类解析 的时候是否还记得这两个方法&#xff1a;parseLookupOverrideSubElements() 和 parseReplacedMethodSubElements() 这两个方法分别用于解析 lookup-method 和 replaced-method。parseLookupOverrideSubElements() 源码如下&#xff1a;
更多关于 lookup-method 和 replaced-method 请看&#xff1a;【死磕 Spring】----- IOC 之解析 bean 标签&#xff1a;meta、lookup-method、replace-method
类 CglibSubclassingInstantiationStrategy 为 Spring 实例化 bean 的默认实例化策略&#xff0c;其主要功能还是对父类功能进行补充&#xff1a;其父类将 CGLIB 的实例化策略委托其实现。
--- SimpleInstantiationStrategy
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, &#64;Nullable String beanName, BeanFactory owner)
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
--- CglibSubclassingInstantiationStrategy
&#64;Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, &#64;Nullable String beanName, BeanFactory owner)
return instantiateWithMethodInjection(bd, beanName, owner, null);
CglibSubclassingInstantiationStrategy 实例化 bean 策略是通过其内部类 CglibSubclassCreator 来实现的。
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, &#64;Nullable String beanName, BeanFactory owner,
&#64;Nullable Constructor<?> ctor, &#64;Nullable Object... args)
return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
创建 CglibSubclassCreator 实例然后调用其 instantiate()&#xff0c;该方法用于动态创建子类实例&#xff0c;同时实现所需要的 lookups&#xff08;lookup-method、replace-method&#xff09;。
public Object instantiate(&#64;Nullable Constructor<?> ctor, &#64;Nullable Object... args)
Class<?> subclass &#61; createEnhancedSubclass(this.beanDefinition);
Object instance;
if (ctor &#61;&#61; null)
instance &#61; BeanUtils.instantiateClass(subclass);
else
try
Constructor<?> enhancedSubclassConstructor &#61; subclass.getConstructor(ctor.getParameterTypes());
instance &#61; enhancedSubclassConstructor.newInstance(args);
catch (Exception ex)
throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
"Failed to invoke constructor for CGLIB enhanced subclass [" &#43; subclass.getName() &#43; "]", ex);
//这个地方解决一个bug&#xff0c;bug提交报告https://jira.spring.io/browse/SPR-10785
// SPR-10785: set callbacks directly on the instance instead of in the
// enhanced class (via the Enhancer) in order to avoid memory leaks.
Factory factory &#61; (Factory) instance;
factory.setCallbacks(new Callback[] NoOp.INSTANCE,
new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner));
return instance;
调用 createEnhancedSubclass() 为提供的 BeanDefinition 创建 bean 类的增强子类。
private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition)
// cglib里面的用法&#xff0c;对原始class进行增强&#xff0c;并设置callback
Enhancer enhancer &#61; new Enhancer();
enhancer.setSuperclass(beanDefinition.getBeanClass());
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
if (this.owner instanceof ConfigurableBeanFactory)
ClassLoader cl &#61; ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
// 过滤&#xff0c;自定义逻辑来指定调用的callback下标
enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
enhancer.setCallbackTypes(CALLBACK_TYPES);
return enhancer.createClass();
获取子类增强 class 后&#xff0c;如果 Constructor 实例 ctr 为空&#xff0c;则调用默认构造函数&#xff08;BeanUtils.instantiateClass()&#xff09;来实例化类&#xff0c;否则则根据构造函数类型获取具体的构造器&#xff0c;调用 newInstance() 实例化类。在 createEnhancedSubclass() 我们注意两行代码&#xff1a;
enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
enhancer.setCallbackTypes(CALLBACK_TYPES);
通过 MethodOverrideCallbackFilter 来定义调用 callback 类型&#xff0c;MethodOverrideCallbackFilter 是用来定义 CGLIB 回调过滤方法的拦截器行为&#xff0c;它继承 CglibIdentitySupport 实现 CallbackFilter 接口&#xff0c; CallbackFilter 是 CGLIB 的一个回调过滤器&#xff0c;CglibIdentitySupport 则为 CGLIB 提供 hashCode() 和 equals() 方法&#xff0c;以确保 CGLIB 不会为每个 bean 生成不同的类。MethodOverrideCallbackFilter 实现 CallbackFilter accept()&#xff1a;
public int accept(Method method)
MethodOverride methodOverride &#61; getBeanDefinition().getMethodOverrides().getOverride(method);
if (logger.isTraceEnabled())
logger.trace("Override for &#39;" &#43; method.getName() &#43; "&#39; is [" &#43; methodOverride &#43; "]");
if (methodOverride &#61;&#61; null)
return PASSTHROUGH;
else if (methodOverride instanceof LookupOverride)
return LOOKUP_OVERRIDE;
else if (methodOverride instanceof ReplaceOverride)
return METHOD_REPLACER;
throw new UnsupportedOperationException("Unexpected MethodOverride subclass: " &#43;
methodOverride.getClass().getName());
根据 BeanDefinition 中定义的 MethodOverride 不同&#xff0c;返回不同的值&#xff0c; 这里返回的 PASSTHROUGH 、LOOKUP_OVERRIDE、METHOD_REPLACER 都是 Callbak 数组的下标&#xff0c;这里对应的数组为 CALLBACK_TYPES 数组&#xff0c;如下&#xff1a;
private static final Class<?>[] CALLBACK_TYPES &#61; new Class<?>[]
NoOp.class, LookupOverrideMethodInterceptor.class, ReplaceOverrideMethodInterceptor.class;
这里又定义了两个熟悉的拦截器 &#xff1a;LookupOverrideMethodInterceptor 和 ReplaceOverrideMethodInterceptor&#xff0c;两个拦截器分别对应两个不同的 callback 业务&#xff1a;
private static class LookupOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor
private final BeanFactory owner;
public LookupOverrideMethodInterceptor(RootBeanDefinition beanDefinition, BeanFactory owner)
super(beanDefinition);
this.owner &#61; owner;
&#64;Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable
// Cast is safe, as CallbackFilter filters are used selectively.
LookupOverride lo &#61; (LookupOverride) getBeanDefinition().getMethodOverrides().getOverride(method);
Assert.state(lo !&#61; null, "LookupOverride not found");
Object[] argsToUse &#61; (args.length > 0 ? args : null); // if no-arg, don&#39;t insist on args at all
if (StringUtils.hasText(lo.getBeanName()))
return (argsToUse !&#61; null ? this.owner.getBean(lo.getBeanName(), argsToUse) :
this.owner.getBean(lo.getBeanName()));
else
return (argsToUse !&#61; null ? this.owner.getBean(method.getReturnType(), argsToUse) :
this.owner.getBean(method.getReturnType()));
private static class ReplaceOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor
private final BeanFactory owner;
public ReplaceOverrideMethodInterceptor(RootBeanDefinition beanDefinition, BeanFactory owner)
super(beanDefinition);
this.owner &#61; owner;
&#64;Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable
ReplaceOverride ro &#61; (ReplaceOverride) getBeanDefinition().getMethodOverrides().getOverride(method);
Assert.state(ro !&#61; null, "ReplaceOverride not found");
// TODO could cache if a singleton for minor performance optimization
MethodReplacer mr &#61; this.owner.getBean(ro.getMethodReplacerBeanName(), MethodReplacer.class);
return mr.reimplement(obj, method, args);
通过这两个拦截器&#xff0c;再加上这篇博客&#xff1a;【死磕 Spring】----- IOC 之解析 bean 标签&#xff1a;meta、lookup-method、replace-method&#xff0c;是不是一道绝佳的美食。